import React from 'react';
import classNames from 'classnames';
import Icon from '../Icon';
import './Drawer.less';

class Drawer extends React.Component {
    displayName = 'Drawer';

    static defaultProps = {
        width: 256,
        closeable: true
    }

    state = {
        open: this.props.visible
    }

    lastOpen = this.props.visible;

    componentDidUpdate () {
        if (this.lastOpen !== this.state.open) {
            if (this.state.open) {
                this.box.classList.add('cm-drawer-visible');
                setTimeout(() => {
                    this.box.classList.add('cm-drawer-open');
                }, 0);
            } else {
                this.box.classList.remove('cm-drawer-open');
                setTimeout(() => {
                    this.box.classList.remove('cm-drawer-visible');
                }, 250);
            }
            this.lastOpen = this.state.open;
        }
    }

    static getDerivedStateFromProps (nextProps, state) {
        const {visible} = nextProps;
        if (visible !== state.open) {
            return {
                open: visible
            };
        }
        return null;
    }

    onShadowClick = () => {
        if (this.props.closeable) {
            if (this.props.onClose) {
                this.props.onClose();
            }
        }
    }

    render () {
        const {className, style, align, width, title, children, closeable} = this.props;
        const clazzName = classNames('cm-drawer', className, {
            [`cm-drawer-${align}`]: align
        });
        return <div className={clazzName} style={style} ref={f => this.box = f}>
            <div className='cm-drawer-shadow' onClick={this.onShadowClick}></div>
            <div className='cm-drawer-wrap' style={{width}}>
                {
                    title 
                        ? <div className='cm-drawer-title'>
                            {title}
                            {
                                closeable ? null
                                    : <Icon name='x' size={18} className='cm-drawer-close' onClick={this.props.onClose}/>
                            }
                        </div>
                        : null
                }
                <div className='cm-drawer-body'>
                    {children}
                </div>
            </div>
        </div>;
    }
}

export default Drawer;
